package com.nuoniu.sibanyun.service.production.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.bo.VProductionWorkDetailBo;
import com.nuoniu.sibanyun.entity.production.VProductionWorkDetail;
import com.nuoniu.sibanyun.entity.production.VProductionWorkInventoryDetail;
import com.nuoniu.sibanyun.entity.production.VProductionWorkMain;
import com.nuoniu.sibanyun.entity.production.VProductionWorkProcedureDetail;
import com.nuoniu.sibanyun.entity.vo.VProductionWorkDetailSimpleVo;
import com.nuoniu.sibanyun.entity.vo.VProductionWorkProcedureDetailVo;
import com.nuoniu.sibanyun.mapper.production.VProductionWorkDetailMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.production.IVProductionWorkDetailService;
import com.nuoniu.sibanyun.service.production.IVProductionWorkInventoryDetailService;
import com.nuoniu.sibanyun.service.production.IVProductionWorkProcedureDetailService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 生产加工单明细 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2021-03-13
 */
@Service
@Log4j2
public class VProductionWorkDetailServiceImpl extends ServiceImpl<VProductionWorkDetailMapper, VProductionWorkDetail> implements IVProductionWorkDetailService {

    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private IVProductionWorkInventoryDetailService productionWorkInventoryDetailService;
    @Autowired
    private IVProductionWorkProcedureDetailService productionWorkProcedureDetailService;


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void batchSave(VProductionWorkMain productionWorkMain) {
        List<VProductionWorkDetail> productionWorkDetailList = productionWorkMain.getOrderDetailList();
        Long mainId = productionWorkMain.getId();
        String voucherCode = productionWorkMain.getVoucherCode();
        Integer officeId = productionWorkMain.getOfficeId();
        String officeName = productionWorkMain.getOfficeName();
        if(null == productionWorkDetailList || productionWorkDetailList.size() == 0)
            throw new NuoNiuException("生产加工单明细不能为空");
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        List<Long> detailIds = new ArrayList<>();
        productionWorkDetailList.forEach(p -> {
            p.setOrderId(mainId.intValue());
            p.setMainVoucherCode(voucherCode);
            p.setOfficeId(officeId);
            p.setOfficeName(officeName);
            p.setAccountId(currentAccountId);
            p.setCompanyId(userInfo.getCompanyId());
            //添加 不删除的明细ID
            if (p.getId() != null) {
                detailIds.add(p.getId());
            }
        });
        /********  删除明细 *******/
        this.deleteBatchFromMainIdAndNotInDetailIds(mainId,detailIds);
        /********  保存单据明细表 *******/
        this.saveOrUpdateBatch(productionWorkDetailList);
        /********  保存 材料明细  *******/
        productionWorkInventoryDetailService.batchSave(productionWorkMain,detailIds);
        /********  保存 工序明细  *******/
        productionWorkProcedureDetailService.batchSave(productionWorkMain,detailIds);

    }

    @Override
    public VProductionWorkDetailSimpleVo getVProductionWorkDetailSimpleVo(Long productionWorkId) {
        List<VProductionWorkInventoryDetail> productionWorkInventoryDetailList = productionWorkInventoryDetailService.listByProductionWorkId(productionWorkId);
        List<VProductionWorkProcedureDetailVo> productionWorkProcedureDetailList = productionWorkProcedureDetailService.listByProductionWorkId(productionWorkId);
        VProductionWorkDetailSimpleVo workDetailSimpleVo = new VProductionWorkDetailSimpleVo();
        workDetailSimpleVo.setInventoryDetails(productionWorkInventoryDetailList);
        workDetailSimpleVo.setProcedureDetails(productionWorkProcedureDetailList);
        return workDetailSimpleVo;
    }


    @Override
    public List<Integer> getDetailByMainId(Integer mainId) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        List<Integer> detailIds = baseMapper.getDetailByMainId(userInfo.getCompanyId(), currentAccountId, mainId);
        return detailIds;
    }

    @Override
    public List<VProductionWorkDetail> getDetailsByOrderId(Long orderId) {
        QueryWrapper<VProductionWorkDetail> queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_id",orderId);
        List<VProductionWorkDetail> list = list(queryWrapper);
        return list;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void removeByOrderId(Long orderId) {
        QueryWrapper<VProductionWorkDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);
        remove(queryWrapper);
        /** 删除 材料明细*/
        productionWorkInventoryDetailService.deleteFromMainId(orderId);
        /** 删除 工序明细*/
        productionWorkProcedureDetailService.deleteFromMainId(orderId);
    }


    @Override
    public VProductionWorkDetailBo getVProductionWorkDetailBo(Integer id) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        VProductionWorkDetailBo vProductionWorkDetailBo = baseMapper.getVProductionWorkDetailBo(userInfo.getCompanyId(), currentAccountId, id);
        return vProductionWorkDetailBo;
    }

    @Override
    public List<VProductionWorkDetail> listNotDispatchedDetail(Integer mainId) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        List<VProductionWorkDetail> vProductionWorkDetails = baseMapper.listNotDispatchedDetail(userInfo.getCompanyId(), currentAccountId, mainId);
        return vProductionWorkDetails;
    }

    @Override
    public List<VProductionWorkDetail> listNotDispatchedDetail2(Integer mainId) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        List<VProductionWorkDetail> vProductionWorkDetails = baseMapper.listNotDispatchedDetail2(userInfo.getCompanyId(), currentAccountId, mainId);
        return vProductionWorkDetails;
    }

    /**
     * 更新产品累计派遣数量()
     * @param id     加工单产品明细ID
     * @param offset 偏移量 ( 未负数的时候，可以更新加工单状态 )
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateCumDispatchQuantity(Integer id, BigDecimal offset) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        VProductionWorkDetailBo detailBo = getVProductionWorkDetailBo(id);
        Integer mainVoucherState = detailBo.getMainVoucherState();
        if ( 0 == mainVoucherState){
            throw new NuoNiuException("加工单未审核");
        }
        //
        if (offset.compareTo(BigDecimal.ZERO) > 0 && 10 == mainVoucherState){
            throw new NuoNiuException("加工单已经关闭");
        }

        BigDecimal cumDispatchQuantity = detailBo.getCumDispatchQuantity();
        if (null == cumDispatchQuantity){
            cumDispatchQuantity = new BigDecimal(0);
        }
        cumDispatchQuantity = cumDispatchQuantity.add(offset);
        BigDecimal baseQuantity = detailBo.getBaseQuantity();
        BigDecimal afterAvailableDispatchQuantity = baseQuantity.subtract(cumDispatchQuantity);
        BigDecimal availableDispatchQuantity = baseQuantity.subtract(null == detailBo.getCumDispatchQuantity() ? BigDecimal.ZERO : detailBo.getCumDispatchQuantity());
        if (afterAvailableDispatchQuantity.compareTo(BigDecimal.ZERO) < 0 )throw new NuoNiuException("派遣数量已经超过产品生产数量,目前可派遣数量:"+ availableDispatchQuantity);
//        if(afterAvailableDispatchQuantity.compareTo(BigDecimal.ZERO) == 0){
//            //关闭 来源加工单
//            productionWorkMainService.updateVoucherState(detailBo.getMainId(),10);
//        }else if(afterAvailableDispatchQuantity.compareTo(BigDecimal.ZERO) > 0 ){
//            if(offset.compareTo(BigDecimal.ZERO) < 0){
//                //更新 来源加工单 状态
//                productionWorkMainService.updateVoucherState(detailBo.getMainId(),1);
//            }
//        }
        boolean b = baseMapper.updateCumDispatchQuantity(userInfo.getCompanyId(), currentAccountId, id, offset);
        if (!b){
            throw new NuoNiuException("更新失败，请重试");
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteBatchFromMainIdAndNotInDetailIds(Long mainId, List<Long> detailIds) {
        QueryWrapper<VProductionWorkDetail> wrapper = new QueryWrapper();
        wrapper.eq("order_id", mainId);
        if (detailIds.size() > 0) {
            wrapper.notIn("id", detailIds);
        }
        remove(wrapper);
    }
}
